<template>
	<view class="content">
		<z-paging ref="pagingRef" v-if="firstLoaded || isCurrentPage" v-model="dataList" @query="queryList"
			:fixed="false" :empty-config="{tip: '暂无数据'}">
			<view class="item" :style="bgStyle" v-for="(item, index) in dataList" :key="index" @click="itemClick(item)">
				<view class="uni-flex">
					<text class="text1">{{item.name}}</text>
					<view class="uni-flex uni-align-center xing_box" v-if="item.isRecommended==='1'">
						<image :src="`${$ImgBaseUrl}part_time_xing.png`" mode="widthFix" />
						<text class="text2">平台推荐</text>
					</view>
				</view>

				<text v-if='item.labels.length>0'
					v-for="(label, i) in Array.isArray(item.labels) ? item.labels : (item.labels || '').split(',')"
					:key="i" class="project">
					{{ label }}
				</text>
				<text v-else>--</text>
				<view class="uni-flex uni-justify-between uni-align-center line3">
					<view>
						<text class="money">¥{{item.price}}</text>
						<!-- <text class="money_tip">元/小时</text> -->
					</view>
					<view class="sign-up" @click.stop="ContactEmployer(item)">联系雇主</view>
				</view>
			</view>
			<!-- 设置自己的empty组件，非必须。空数据时会自动展示空数据组件，不需要自己处理 -->
			<template #empty>
				<!-- 空数据提示，添加居中样式 -->
				<view class="empty-container">
					<view class="empty-content">暂无数据</view>
				</view>
			</template>
		</z-paging>
		<CallDialog :showDialog="showCallDialog" :phoneNumber="phoneNumber" @close="showCallDialog = false">
		</CallDialog>
	</view>
</template>

<script setup>
	import {
		querypartTimeJobList
	} from "@/api/findPartTimeJob.js";
	import {
		getUserEncryption
	} from '@/api/findPeople.js'
	import {
		getAreaid,
		getCityCode
	} from "@/common/util.js";
	import CallDialog from '@/components/CallDialog.vue'
	import {
		ref,
		watch,
		nextTick,
		reactive,
		onMounted,
		onUnmounted,
		computed
	} from "vue";
	import {
		ImgBaseUrl
	} from "@/utils/domain.js";
	const showCallDialog = ref(false)
	const phoneNumber = ref(''); // 初始默认号码
	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0
		},
		currentIndex: {
			type: Number,
			default: 0
		},
		currentId: {
			type: Number,
			default: 0
		},
		jobName: {
			type: String,
			default: ''
		}
	});

	const bgStyle = computed(() => ({
		backgroundImage: `url(${ImgBaseUrl}part_time_item_bg.png)`,
	}));

	const emit = defineEmits(["reload"]);
	const dataList = ref([]);
	const firstLoaded = ref(false);
	const isCurrentPage = ref(false);
	const pagingRef = ref(null);
	const state = reactive({
		currentAreaId: ""
	});

	// 监听currentId变化（核心：标签切换时重新请求）
	// watch(
	// 	() => props.currentId,
	// 	(newId) => {
	// 		if (newId && props.currentIndex === props.tabIndex) {
	// 			// 当标签ID变化且当前标签可见时刷新
	// 			pagingRef.value?.reload();
	// 		}
	// 	}, {
	// 		immediate: true
	// 	} // 初始加载时触发
	// );

	// 监听区域选择事件
	const handleAreaChange = async (data) => {
		if (data?.areaId) {
			state.currentAreaId = data.areaId;
			await nextTick();
			pagingRef.value?.reload();
		}
	};

	// 监听当前标签可见性
	watch(
		() => props.currentIndex,
		(newVal) => {
			if (newVal === props.tabIndex) {
				if (!firstLoaded.value) {
					nextTick(() => {
						setTimeout(() => {
							isCurrentPage.value = true;
						}, 100);
					});
				} else {
					// 已加载过的标签再次可见时刷新
					pagingRef.value?.refresh();
				}
			}
		}, {
			immediate: true
		}
	);

	// 刷新方法
	const reload = () => {
		nextTick(() => {
			pagingRef.value?.reload(); // 重置页码并刷新
		});
	};
	defineExpose({
		reload
	});
	// 联系雇主
	const ContactEmployer = async (item) => {
		const user_info = uni.getStorageSync('user_info');
		if (user_info) {
			const id = JSON.parse(user_info).id
			if (id === item.userId) {
				uni.showToast({
					title: '不能联系自己发布的兼职',
					icon: 'none'
				})
			} else {
				showCallDialog.value = true
				try {
					const res = await getUserEncryption(item.userId);
					console.log('获取加密号码接口返回', res);
					if (res.code === 200) {
						phoneNumber.value = res.data
					}
					// 假设接口返回的加密号码字段是 encryptionPhone，根据实际接口调整

				} catch (err) {
					console.error('获取加密号码失败', err);
				}
			}
		}

	}
	// 列表请求（完善空数据处理）
	const queryList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum,
				pageSize,
				cityCode: state.currentAreaId || getCityCode(),
				categoryId: decodeURIComponent(props.currentId),
				jobName: props.jobName || ''
			};
			console.log('请求参数:', params);
			const res = await querypartTimeJobList(params);
			// 明确处理空数组情况
			const result = res?.rows || [];
			if (result.length === 0) {
				// 空数据时强制清空列表并显示空视图
				dataList.value = [];
				pagingRef.value?.complete([], {
					noMore: true
				}); // 标记无更多数据
			} else {
				pagingRef.value?.complete(result);
			}
			firstLoaded.value = true;
		} catch (error) {
			console.error("请求失败:", error);
			pagingRef.value?.complete(false);
		}
	};

	onMounted(() => {
		uni.$off('areaSelected', handleAreaChange);
		uni.$on('areaSelected', handleAreaChange);
	});

	onUnmounted(() => {
		uni.$off('areaSelected', handleAreaChange);
	});

	const itemClick = (item) => {
		uni.navigateTo({
			url: `/pages/tabBars/findPartTimeJob/partTimeDetail?id=${item.id}`
		});
	};
</script>
<style lang="scss" scoped>
	.content {
		height: calc(100vh - 200rpx);
	}

	.item {
		background-size: 100% auto;
		/* 宽度100%，高度自动 */
		background-repeat: no-repeat;
		background-position: top center;
		/* 关键：图片顶部对齐 */
		padding: 30rpx 20rpx;
		margin: 26rpx 24rpx 0;
		border-radius: 20rpx;

		.text1 {
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
			margin-bottom: 20rpx;
		}

		.xing_box {
			margin: 0 0 17rpx 19rpx;

			image {
				width: 47rpx;
				height: 47rpx;
			}

			.text2 {
				font-weight: 500;
				font-size: 24rpx;
				color: #fe9010;
				background: #fff5e0;
				border-radius: 0px 21px 21px 0px;
				padding: 5rpx 10rpx;
			}
		}

		.project {
			font-weight: 500;
			font-size: 24rpx;
			color: #333333;
			background: #f1f1f1;
			border-radius: 4px;
			margin-right: 17rpx;
			padding: 10rpx;
		}

		.line3 {
			margin-top: 10rpx;

			.money {
				font-size: 34rpx;
				color: #ff6a47;
				margin-right: 10rpx;
			}

			.money_tip {
				font-size: 20rpx;
				color: #999999;
			}

			.sign-up {
				background: #2f80ed;
				border-radius: 34rpx;
				font-weight: 500;
				font-size: 30rpx;
				color: #ffffff;
				padding: 14rpx 36rpx;
			}
		}
	}

	/* 空数据样式 - 关键修改 */
	.empty-container {
		/* 让容器占满整个可用空间 */
		min-height: 120rpx;
		/* 可根据实际需求调整高度 */
		width: 100%;
		/* 启用flex布局实现居中 */
		display: flex;
		justify-content: center;

	}
</style>